<?php
namespace Admin\Controller;
use Admin\Controller\BaseController;

class LogicClassController extends BaseController {

	public function index() {
		$logicClasses = D('LogicClass')->relation(array('teacher', 'course'))->select();
		$this->assign('logic_classes', $logicClasses);
		$this->display();
	}

	public function add() {
		$teachers = D('Teacher')->relation('academy')->select();
		$courses = D('Course')->relation('major')->select();
		$this->assign('teachers', $teachers);
		$this->assign('courses', $courses);
		$this->display();
	}

	public function addPost() {
		if(!IS_POST) {
			$this->redirect('LogicClass/index');
		}
		$data['teacher_id'] = I('post.teacher_id');
		$data['course_id'] = I('post.course_id');
		$data['class'] = I('post.class');
		$logicClass = D('LogicClass');
		if(!$logicClass->data($data)->create()) {
			$this->error($logicClass->getError());
		}
		if(!$logicClass->checkUnique($logicClass->data())) {
			$this->error('逻辑班级已存在！');
		}
		$teacher = M('Teacher')->where(array('id' => $data['teacher_id']))->find();
		$course = M('Course')->where(array('id' => $data['course_id']))->find();
		$data['name'] = $teacher['name'] . ' ' . $course['name'] . ' ' . $data['class'] . '班';
		if(!$logicClass->data($data)->add()) {
			$this->error('数据写入失败！');
		}
		$this->success('添加成功！', U('LogicClass/index'));
	}

	public function deletePost() {
		if(!IS_POST) {
			$this->redirect('LogicClass/index');
		}
		$id = I('post.id');
		$logicClass = D('LogicClass');
		if($logicClass->hasChildObj($id)) {
			$this->error($logicClass->getError());
		}
		if(M('LogicClass')->where(array('id' => $id))->delete()) {
			$this->success('删除成功！', U('LogicClass/index'), 0);
		} else {
			$this->error('删除失败！');
		}
	}

	public function test() {
		$logicClasses = D('LogicClass')->relation(array('teacher', 'course'))->find();
		$teacher = D('LogicClass')->relationGet('teacher');
		dump($teacher);
	}

}
